# crud/sys_api_project.py
from sqlalchemy.orm import Session
from typing import List, Optional
from src.models import sys_api_project as models
from src.schemas import sys_api_project as schemas
from src import logger_cust


def get_api_project(db: Session, project_id: str):
    return db.query(models.SysApiProject).filter(models.SysApiProject.id == project_id).first()


def get_api_projects(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.SysApiProject).offset(skip).limit(limit).all()


def create_api_project(db: Session, project: schemas.SysApiProjectCreate):
    db_project = models.SysApiProject(**project.dict())
    db.add(db_project)
    db.commit()
    db.refresh(db_project)
    return db_project


def create_api_projects(db: Session, projects: list[schemas.SysApiProjectCreate]):
    try:
        db_projects = [models.SysApiProject(**project.dict()) for project in projects]
        db.add_all(projects)
        db.commit()
        for db_project in db_projects:
            db.refresh(db_project)
        return db_projects
    except Exception as e:
        db.rollback()
        raise e


def update_api_project(db: Session, project_id: str, project: schemas.SysApiProjectUpdate):
    db_project = db.query(models.SysApiProject).filter(models.SysApiProject.id == project_id).first()
    if db_project:
        update_data = project.dict(exclude_unset=True)
        db.query(models.SysApiProject).filter(models.SysApiProject.id == project_id).update(update_data)
        db.commit()
        db.refresh(db_project)
    return db_project


def delete_api_project(db: Session, project_id: str):
    db_project = db.query(models.SysApiProject).filter(models.SysApiProject.id == project_id).first()
    if db_project:
        db.delete(db_project)
        db.commit()


#  初始化资料源
def ini_get_api_project_by_api_code(db: Session, api_code: str | None):
    query = db.query(models.SysApiProject)
    if api_code is not None:  # 非空才过滤
        return query.filter(models.SysApiProject.api_code == api_code).first() is not None
    return query.all()  # 空串/None 返回全部


def ini_create_api_project(db: Session, project: schemas.SysApiProjectCreate):
    db_project = models.SysApiProject(**project.dict())
    db.add(db_project)
    db.commit()
    db.refresh(db_project)
    return db_project


def ini_api_project(db: Session):
    api_project = ini_get_api_project_by_api_code(db, "api")

    if not api_project:
        ini_create_api_project(db, schemas.SysApiProjectCreate(
            name="API",
            api_code="api",
            api_secret="api",
            api_url="",
            api_status=True,
        ))
        logger_cust.debug("sys_mangers-init_project:默认项目 'apiAdmin' 已添加到 sys_api_project 表中。")
    else:
        logger_cust.info("sys_mangers-init_project:默认项目 'apiAdmin' 已存在，无需操作。")
